const baseurl = 'https://xdapi.yaoxuedao.com.cn/api'
// const baseurl = 'https://xdapi.yaoxuedao.com.cn/testapi'
// const baseurl = 'http://192.168.8.126:9876'


const request = (url, options) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseurl}${url}`, //域名接口地址
      method: options.method, //配置method方法
      data: options.method === 'GET' ? options.data : JSON.stringify(options.data), //如果是GET,GET自动让数据成为query String,其他方法需要让options.data转化为字符串
      header: {
        'Content-Type': '',
        // 'token':'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxNTY1MjUxMjkwOCJ9.sADt8UYwkE6tOLNmDUOqpZEpH-1NCiI7kNreA-wwAu4'
        'token': wx.getStorageSync('Xd_Token') ? wx.getStorageSync('Xd_Token') : ''
      }, //header中可以添加token值等
      success(request) { //监听成功后的操作
        if (request.statusCode === 200) {
          resolve(request.data)
        } else {
          reject(request.data)
        }
        let token = wx.getStorageSync('Xd_Token')
        if (request.data.msg == '登录已过期，请重新登录') {
          wx.showToast({
            title: '登录中...',
            icon:'none'
          })
          wx.clearStorageSync()
          wx.login({
            success: res => {
              console.log(res)
              if (res.code) {
                wx.request({
                  url: baseurl + '/user/appletAuth',
                  method: 'POST',
                  data: {
                    code: res.code
                  },
                  success: (res => {
                    console.log(res)
                    var token = res.data.data.token
                    wx.setStorageSync('Xd_Token', token)
                    var userNumber = res.data.data.userBO.phone
                    wx.setStorageSync('userNumber', userNumber)
                    var userBO = res.data.data.userBO
                    wx.setStorageSync('userInfo', userBO)
                    wx.switchTab({
                      url: '/pages/index/index',
                    })
                  })
                })
              }
            }
          })
        }
      },
      fail(error) { //返回失败也同样传入reject()方法
        reject(error.data)
      }
    })
  })
}

//封装get方法
const get = (url, options = {}) => {
  return request(url, {
    method: 'GET',
    data: options
  })
}
//封装post方法
const post = (url, options) => {
  return request(url, {
    method: 'POST',
    data: options
  })
}
//封装put方法
const put = (url, options) => {
  return request(url, {
    method: 'PUT',
    data: options
  })
}
//封装del方法
const del = (url, options) => {
  return request(url, {
    method: 'DELETE',
    data: options
  })
}

module.exports = {
  get,
  post,
  put,
  del
}